//
//  HNSH_AgentViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/28.
//

#import "HNSH_AgentViewController.h"

#import "HNSH_AgentItemVIew.h"
#import "HNSH_AgentAddressView.h"

#import "HNSH_AddressModel.h"

#import "HNSH_AgentHeaderView.h"
#import "HNSH_AgentBottomView.h"
#import "ST_PayPasswordView.h"

@interface HNSH_AgentViewController ()<HNSH_AgentAddressViewDelegate>

/* nameView */
@property (nonatomic, strong) HNSH_AgentItemVIew *nameView;
/* idCardView */
@property (nonatomic, strong) HNSH_AgentItemVIew *idCardView;
/* phoneView */
@property (nonatomic, strong) HNSH_AgentItemVIew *phoneView;
/* nameString */
@property (nonatomic, copy) NSString *nameString;
/* idCardString */
@property (nonatomic, copy) NSString *idCardString;
/* phoneString */
@property (nonatomic, copy) NSString *phoneString;

/* addressLabel */
@property (nonatomic, strong) UILabel *addressLabel;

/* statusLabel */
@property (nonatomic, strong) UILabel *statusLabel;

/* addressModel */
@property(nonatomic, strong) HNSH_AddressModel *addressModel;

/* addBtn */
@property (nonatomic, strong) UIButton *addBtn;

/* region_code */
@property (nonatomic, copy) NSString *region_code;

@end

@implementation HNSH_AgentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.nameString = @"";
    self.idCardString = @"";
    self.phoneString = @"";
    
    [self showNavTitle:@"我的代理" showLeftItem:YES];
    
    self.view.backgroundColor = [UIColor appWhiteLabelColor];
    
    [self configUI];
    
    [self loadAgentInfo];
}

- (void)configUI {
    UILabel *statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth-94, kStatusBarHeight, 94, 44)];
    statusLabel.text = @"申请中";
    statusLabel.textColor = [UIColor appGreenColor];
    statusLabel.font = [UIFont boldSystemFontOfSize:18];
    statusLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:statusLabel];
    statusLabel.hidden = YES;
    self.statusLabel = statusLabel;
    
    self.nameView = [[HNSH_AgentItemVIew alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 50)];
    self.nameView.titleLabel.text = @"姓名：";
    self.nameView.placeholder = @"请输入姓名";
    [self.view addSubview:self.nameView];
    
    self.idCardView = [[HNSH_AgentItemVIew alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight+50, kScreenWidth, 50)];
    self.idCardView.titleLabel.text = @"身份证号：";
    self.idCardView.placeholder = @"请输入身份证号";
    [self.view addSubview:self.idCardView];
    
    self.phoneView = [[HNSH_AgentItemVIew alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight+100, kScreenWidth, 50)];
    self.phoneView.titleLabel.text = @"联系电话：";
    self.phoneView.placeholder = @"请输入联系电话";
    [self.view addSubview:self.phoneView];
    
    [self configSelectView];
    
    WeakSelf(weakSelf);
    [[self.nameView.textField rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UITextField *field = x;
        weakSelf.nameString = field.text;
    }];
    [[self.idCardView.textField rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UITextField *field = x;
        weakSelf.idCardString = field.text;
    }];
    [[self.phoneView.textField rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UITextField *field = x;
        weakSelf.phoneString = field.text;
    }];
}

- (void)configSelectView {
    UIView *selectView = [[UIView alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight+150, kScreenWidth, 50)];
    selectView.backgroundColor = [UIColor appBGColor];
    [self.view addSubview:selectView];
    selectView.userInteractionEnabled = YES;
    
    UILabel *selectTitleLabel = [[UILabel alloc]init];
    selectTitleLabel.text = @"申请区域：";
    selectTitleLabel.textColor = [UIColor appBlackLabelColor];
    selectTitleLabel.font = [UIFont boldSystemFontOfSize:14];
    [selectView addSubview:selectTitleLabel];
    
    UILabel *selectDesLabel = [[UILabel alloc]init];
    selectDesLabel.text = @"请选择申请区域";
    selectDesLabel.textColor = [UIColor appGrayLabelColor];
    selectDesLabel.font = [UIFont systemFontOfSize:14];
    [selectView addSubview:selectDesLabel];
    self.addressLabel = selectDesLabel;
    
    UIImageView *selectIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_agent_bottom_show"]];
    [selectView addSubview:selectIcon];
    
    [selectTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(28);
        make.top.bottom.mas_equalTo(0);
    }];
    [selectDesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(selectTitleLabel.mas_right).offset(0);
        make.top.bottom.mas_equalTo(0);
    }];
    [selectIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-51);
        make.centerY.equalTo(selectView.mas_centerY);
        make.width.mas_equalTo(9);
        make.height.mas_equalTo(6);
    }];
    
    WeakSelf(weakSelf);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf chooseAddress];
    }];
    [selectView addGestureRecognizer:tap];
    
    HNSH_AgentBottomView *bottomView = [[HNSH_AgentBottomView alloc]initWithFrame:CGRectMake(16, 224+kNavBarAndStatusBarHeight, kScreenWidth-32, 120)];
    [self.view addSubview:bottomView];
    
    
    [self.view addSubview:self.addBtn];
}

- (void)configAgentHeaderWithDict:(NSDictionary *)dict {
    HNSH_AgentHeaderView *view = [[HNSH_AgentHeaderView alloc]initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight-kNavBarAndStatusBarHeight)];
    view.dict = dict;
    [self.view addSubview:view];
}

#pragma mark network
- (void)loadAgentInfo {
    [HNSH_UserNetServer requestAgentDataSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            //代理状态 10:待审批 20:审批不通过 100:审批通过 110:已禁用 120:已到期
            self.statusLabel.hidden = NO;
            if ([responseObject.resultset[@"status"] integerValue] == 10) {
                self.statusLabel.text = @"待审批";
            } else if ([responseObject.resultset[@"status"] integerValue] == 20) {
                self.statusLabel.text = @"审批不通过";
                self.statusLabel.frame = CGRectMake(kScreenWidth-114, kStatusBarHeight, 114, 44);
                self.statusLabel.textColor = [UIColor appGreenColor];
            } else if ([responseObject.resultset[@"status"] integerValue] == 100) {
//                self.statusLabel.text = @"审批通过";
                self.statusLabel.hidden = YES;
                [self configAgentHeaderWithDict:responseObject.resultset];
            } else if ([responseObject.resultset[@"status"] integerValue] == 110) {
                self.statusLabel.text = @"已禁用";
                self.statusLabel.textColor = [UIColor appGreenColor];
            } else if ([responseObject.resultset[@"status"] integerValue] == 120) {
                self.statusLabel.text = @"已到期";
                self.statusLabel.textColor = [UIColor appGreenColor];
            }
            
            //回填数据
            self.addressLabel.text = [NSString stringWithFormat:@"%@%@",responseObject.resultset[@"parent_region_name"],responseObject.resultset[@"region_name"]];
            self.addressLabel.textColor = [UIColor appBlackLabelColor];
            self.addressModel.county_code = [NSString stringWithFormat:@"%@",responseObject.resultset[@"region_code"]];
            
            self.nameString = [NSString stringWithFormat:@"%@",responseObject.resultset[@"name"]];
            self.nameView.textField.text = self.nameString;
            
            self.idCardString = [NSString stringWithFormat:@"%@",responseObject.resultset[@"identity_card_no"]];
            self.idCardView.textField.text = self.idCardString;
            
            self.phoneString = [NSString stringWithFormat:@"%@",responseObject.resultset[@"contact_phone"]];
            self.phoneView.textField.text = self.phoneString;
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)loadPasswordView {
    WeakSelf(weakSelf);
    [ST_PayPasswordView showPasswordViewWithSureBlock:^(NSString * _Nonnull password) {
        [weakSelf loadApplyAgentWithPwd:password];
    } cancelBlock:^{
        
    }];
}

- (void)loadApplyAgentWithPwd:(NSString *)password {
    if (![self.nameString isNotBlank]) {
        [self.view makeToast:@"请输入姓名"];
        return;
    }
    if (![self.idCardString isNotBlank]) {
        [self.view makeToast:@"请输入身份证号"];
        return;
    }
    if (![self.phoneString isNotBlank]) {
        [self.view makeToast:@"请输入手机号"];
        return;
    }
    if (![self.region_code isNotBlank]) {
        [self.view makeToast:@"请选择申请城市"];
        return;
    }
    [HNSH_UserNetServer requestAgentApplyWithAddessCode:self.region_code name:self.nameString identity_card_no:self.idCardString contact_phone:self.phoneString  pay_password:password success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [kSTWindow makeToast:@"申请成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark lazy
- (HNSH_AddressModel *)addressModel{
    if (!_addressModel) {
        _addressModel = [HNSH_AddressModel new];
    }
    return _addressModel;
}

- (UIButton *)addBtn{
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.frame = CGRectMake(30, kScreenHeight - 50 - 23 - kBottomSafeHeight, kScreenWidth - 60, 50);
        [_addBtn setTitle:@"提交申请" forState:UIControlStateNormal];
        [_addBtn setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _addBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _addBtn.backgroundColor = [UIColor appGreenColor];
        _addBtn.layer.cornerRadius = 25;
        _addBtn.layer.masksToBounds = YES;
        [_addBtn addTarget:self action:@selector(loadPasswordView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

-(void)cancelBtnClick:(NSString *)titleAddress titleID:(NSString *)titleID {
    NSLog(@"titleAddress ==> %@  titleID ==> %@",titleAddress,titleID);
    NSArray *titleAry = [titleAddress componentsSeparatedByString:@"/"];
    NSLog(@"ary ==> %@  %@",titleAry,titleAry.lastObject);
    NSString *name = @"";
    for (NSString *str in titleAry) {
        name = [NSString stringWithFormat:@"%@%@",name,str];
    }
    self.addressLabel.text = [NSString stringWithFormat:@"%@", name];
    self.addressLabel.textColor = [UIColor appBlackLabelColor];
    
    NSArray *idAry = [titleID componentsSeparatedByString:@"/"];
    NSLog(@"idAry ==> %@  %@",idAry,idAry.lastObject);
    self.region_code = idAry.lastObject;
}

//MARK: 选择地区
- (void)chooseAddress{
    [self.view endEditing:YES];
    HNSH_AgentAddressView *view = [[HNSH_AgentAddressView alloc]init];
    view.title = @"选择地址";
    view.delegate = self;
    view.defaultHeight = 350;
    view.titleScrollViewH = 37;
    if (view.titleIDMarr.count > 0) {
        view.isChangeAddress = true;
    }
    else{
        view.isChangeAddress = false;
    }
   
    [self.view addSubview:[view initAddressView]];
    [view addAnimate];
    //
//    [DLAddressPickerView showAddressPickerViewWithMaxCom:3 block:^(NSArray * _Nonnull addressArray) {
//        [addressArray enumerateObjectsUsingBlock:^(DLAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if (idx == 0) {
//                self.addressModel.province_code = obj.code;
//                self.addressModel.province_name = obj.name;
//            }
//            if (idx == 1) {
//                self.addressModel.city_code = obj.code;
//                self.addressModel.city_name = obj.name;
//            }
//            if (idx == 2) {
//                self.addressModel.county_code = obj.code;
//                self.addressModel.county_name = obj.name;
//                self.addressLabel.text = [NSString stringWithFormat:@"%@%@%@", self.addressModel.province_name, self.addressModel.city_name, self.addressModel.county_name];
//                self.addressLabel.textColor = [UIColor appBlackLabelColor];
//            }
//        }];
//    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
